//
//  NSObject+SchedBlock.m
//  HX_GTS2
//
//  Created by GC_tandy on 2018/11/30.
//  Copyright © 2018年 gw. All rights reserved.
//

#import "NSObject+SchedBlock.h"

#import <objc/runtime.h>

static NSString *schedCachesKey  = @"schedBlockCachesKey";


@interface NSObject ()

@property (nonatomic,strong) NSMutableDictionary *schedBlockTaskCache;

@end

@implementation NSObject (SchedBlock)

- (NSMutableDictionary *)schedBlockTaskCache{
    NSMutableDictionary *schedBlockTaskCache = objc_getAssociatedObject(self, &schedCachesKey);
    if(schedBlockTaskCache == nil || [schedBlockTaskCache isKindOfClass:[NSMutableDictionary class]] == NO){
        objc_setAssociatedObject(self, &schedCachesKey, [NSMutableDictionary dictionary], OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }
    return objc_getAssociatedObject(self, &schedCachesKey);
}

#define DefaultSchedTime    1
- (void)schedNewTaskBlock:(void(^)(void))taskBlock {
    [self schedNewTaskBlock:taskBlock refreshDelay:DefaultSchedTime];
}

#define NewestBlockTaskKey  @"NewestBlockTaskKey"
- (void)schedNewTaskBlock:(void(^)(void))taskBlock refreshDelay:(NSTimeInterval)delay{
    //把最新的block保存
    [self.schedBlockTaskCache setObject:taskBlock forKey:NewestBlockTaskKey];
    
    NSString *delayKey = @(delay).stringValue;
    //检测要不要发起定时
    if([self.schedBlockTaskCache objectForKey:delayKey] == nil){
        //添加定时标记
        [self.schedBlockTaskCache setObject:delayKey forKey:delayKey];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delay * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            //移除当前定时标记
            [self.schedBlockTaskCache removeObjectForKey:delayKey];
            //定时到了则执行最新的block 执行后移除
            void(^newestTaskBlock)(void) = [self.schedBlockTaskCache objectForKey:NewestBlockTaskKey];
            if(newestTaskBlock){
                [self.schedBlockTaskCache removeObjectForKey:NewestBlockTaskKey];
                newestTaskBlock();
            }
        });
    }
}

@end
                       
